<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="菜单名称">
              <a-input placeholder="请输入" v-model="queryParam.menuName"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="菜单路径">
              <a-input placeholder="请输入" v-model="queryParam.menuUrl"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
              <a-button type="danger" style="margin-left: 8px" @click="newMenu">新增</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <s-table
      ref="table"
      row-key="id"
      size="default"
      :columns="columns"
      :data="loadData"
    >
      <a-icon slot="menuIcon" slot-scope="text" :type="text"></a-icon>
      <div slot="menuButton" slot-scope="text, record">
        <a-tag color="purple" v-if="record.buttonInfoList.length > 0" v-for="(button, index) in record.buttonInfoList" :key="index">{{ button.buttonName }}</a-tag>
        <span v-if="record.buttonInfoList.length === 0">--</span>
      </div>
      <span slot="action" slot-scope="text, record">
        <a @click="handleEdit(record)">编辑</a>
        <a-divider type="vertical" />
        <a-dropdown>
          <a class="ant-dropdown-link">
            更多 <a-icon type="down" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a href="javascript:;" @click="showDetail(record)">详情</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" @click="delMenu(record)">删除</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </s-table>

    <a-modal
      :title="modal.title"
      style="top: 20px;"
      :width="800"
      v-model="modal.visible"
      :confirm-loading="modal.loading"
      @ok="handleOk"
    >
      <a-form class="permission-form" :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="菜单名称"
          style="display: none"
        >
          <a-input
            v-decorator="['id']"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="菜单名称"
        >
          <a-input
            :disabled="this.modal.editType === 2"
            placeholder="起一个名字"
            v-decorator="[
              'menuName',
              {
                rules:[
                  {
                    required: true,
                    message: '请填写菜单名称'
                  },
                  {
                    max: 20,
                    message: '菜单名称长度必须小于20个字符'
                  }
                ]
              }
            ]"
          />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="菜单路径"
          hasFeedback
        >
          <a-input
            :disabled="this.modal.editType === 2"
            placeholder="菜单路径"
            v-decorator="[
              'menuUrl',
              {rules: [{ required: true, message: '请填写菜单路径' },{ max: 255, message: '菜单路径长度必须小于255个字符'} ]}
            ]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="菜单图标"
        >
          <span style="display: inline-block; margin-right: 20px; ">
            <a-icon :type="showIcon" :style="{ fontSize: '30px' }"></a-icon>
          </span>
          <a-popover title="选择图标" trigger="click" v-show="this.modal.editType !== 2">
            <template slot="content">
              <icon-selector style="width: 300px" @change="handleIconChange"/>
            </template>
            <a-button type="primary">
              选择图标
            </a-button>
          </a-popover>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="上级菜单"
        >
          <a-select
            :disabled="this.modal.editType === 2"
            placeholder="上级菜单"
            v-decorator="['pId',{
              rules: [{required: true, message: '请选择上级菜单'}],
              initialValue: -1
            }]"
            @change="handlePid($event)"
          >
            <a-select-option :value="-1">
              顶级菜单
            </a-select-option>
            <a-select-option v-for="top in topMenu" :key="top.id" :value="top.id">
              {{ top.menuName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="菜单排序"
        >
          <a-input-number
            :disabled="this.modal.editType === 2"
            id="inputNumber"
            v-decorator="['orderBy',
                          {rules: [{ required: true, message: '请填写菜单排序' }]}]"
            :min="1"
            :max="200" />
        </a-form-item>

        <a-divider>拥有按钮</a-divider>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="拥有按钮"
        >
          <a-select
            style="width: 100%"
            mode="multiple"
            :allowClear="true"
            v-decorator="['buttonList']"
            :disabled="this.form.getFieldValue('pId') === -1 || this.modal.editType === 2"
          >
            <a-select-option v-for="(button, index) in buttonList" :key="index" :value="button.buttonId">{{ button.buttonName }}</a-select-option>
          </a-select>
        </a-form-item>

      </a-form>
    </a-modal>

  </a-card>
</template>

<script>
  import pick from 'lodash.pick'
  import { STable } from '@/components'
  import { GetMenuList, SaveMenu, DelMenu } from '../../api/systemAdmin'
  import { TopMenu, Buttons } from '../../api/common'
  import IconSelector from '@/myComponents/IconSelector'

  export default {
    name: 'Menu',
    components: {
      STable,
      IconSelector
    },
    data () {
      return {
        modal: {
          title: '',
          visible: false,
          loading: false,
          editType: 0 // 0 新增状态， 1 编辑状态
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        form: this.$form.createForm(this),
        // 查询参数
        queryParam: {},
        // 向后端拉取可以用的操作列表
        buttonList: null,
        // 顶级菜单
        topMenu: null,
        // 选择的图标
        showIcon: 'menu',
        // 如果是顶级菜单，不能选择按钮
        disableSelectButton: false,
        // 表头
        columns: [
          {
            title: '序号',
            width: 80,
            dataIndex: '',
            key: 'rowIndex',
            align: 'center',
            customRender: (t, r, index) => {
              return ((this.paginationInfo.pageNum - 1) * this.paginationInfo.pageSize + index + 1)
            }
          },
          {
            title: '菜单名称',
            dataIndex: 'menuName',
            width: 150
          }, {
            title: '菜单路径',
            dataIndex: 'menuUrl',
            width: 200
          },
          {
            title: '菜单图标',
            dataIndex: 'menuIcon',
            scopedSlots: { customRender: 'menuIcon' },
            width: 100,
            align: 'center'
          },
          {
            title: '菜单按钮',
            dataIndex: 'menuButton',
            scopedSlots: { customRender: 'menuButton' }
          },
          {
            title: '操作',
            width: '130px',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' }
          }
        ],
        paginationInfo: null,
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          this.paginationInfo = parameter
          return GetMenuList(Object.assign(parameter, this.queryParam))
            .then(res => {
              console.log('getMenuList', res)
              if (res.code === 200) {
                return res.result
              } else {
                this.$message.error('获取列表数据出错！')
                return []
              }
            })
        }
      }
    },
    filters: {
    },
    computed: {
    },
    created () {
      Buttons().then(res => {
        console.log('buttons', res)
        if (res.code === 200) {
          this.buttonList = res.result
        } else {
          this.$message.error('查询按钮列表出错！')
        }
      })
      TopMenu().then(res => {
        console.log('topMenu', res)
        if (res.code === 200) {
          this.topMenu = res.result
        } else {
          this.$message.error('查询顶级菜单列表出错！')
        }
      })
    },
    methods: {
      newMenu () {
        this.modal.title = '新增菜单'
        this.form.resetFields()
        this.showIcon = 'menu'
        this.modal.loading = false
        this.modal.editType = 0
        this.modal.visible = true
      },
      handleEdit (record) {
        console.log('record', record)
        this.modal.title = '修改菜单'
        this.modal.loading = false
        this.modal.editType = 1
        this.modal.visible = true
        const buttonList = record.buttonInfoList.map(item => {
          return item.buttonId
        })
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(record, ['id', 'menuName', 'menuUrl', 'pId', 'orderBy']))
          this.form.setFieldsValue({
            'buttonList': buttonList
          })
          this.showIcon = record.menuIcon
        })
      },
      handleOk (e) {
        e.preventDefault()
        this.modal.loading = true
        this.form.validateFields((err, values) => {
          if (err == null) {
            setTimeout(() => {
              values['menuIcon'] = this.showIcon
              console.log(values)
              if (values.buttonList === undefined) {
                values.buttonList = []
              }
              SaveMenu(values).then(res => {
                console.log(res)
                if (res.code === 200) {
                  if (res.msg.indexOf('成功') >= 0) {
                    this.$message.success('保存成功！')
                    this.$refs.table.refresh(true)
                    this.modal.visible = false
                  } else {
                    this.$message.error('保存失败！' + res.msg)
                  }
                } else {
                  this.$message.error('服务出错' + res.msg)
                }
              }).catch(e => {
                this.$message.error('保存失败！')
                console.error(e)
              })
              this.modal.loading = false
            }, 2000)
          } else {
            this.$message.error('存在非法输入！')
            setTimeout(() => {
              this.modal.loading = false
              this.$nextTick(() => { this.modal.loading = false })
            }, 500)
          }
        })
      },
      handleIconChange (icon) {
        this.showIcon = icon
      },
      handlePid (val) {
        if (val === '-1') {
          this.form.setFieldsValue({ 'buttonList': [] })
        }
      },
      delMenu (record) {
        const _this = this
        this.$confirm({
          title: '确定删除这个菜单么',
          // content: 'Some descriptions',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk () {
            DelMenu({ id: record.id }).then(res => {
              if (res.code === 200) {
                if (res.msg.indexOf('成功') >= 0) {
                  _this.$message.success('删除成功！')
                  _this.$refs.table.refresh(true)
                } else {
                  _this.$message.error('删除失败！' + res.msg)
                }
              } else {
                _this.$message.error('服务出错' + res.msg)
              }
            })
          },
          onCancel () {
          }
        })
      },
      showDetail (record) {
        this.modal.title = '菜单详情'
        this.modal.loading = false
        this.modal.editType = 2
        this.modal.visible = true
        console.log('record', record)
        this.$nextTick(() => {
          const buttonList = record.buttonInfoList.map(item => {
            return item.buttonId
          })
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(record, ['id', 'menuName', 'menuUrl', 'pId', 'orderBy']))
            this.form.setFieldsValue({
              'buttonList': buttonList
            })
            this.showIcon = record.menuIcon
          })
        })
      }
    },
    watch: {
    }
  }
</script>

<style lang="less" scoped>
  .permission-form {
    /deep/ .permission-group {
      margin-top: 0;
      margin-bottom: 0;
    }
  }

</style>
